from django.db import IntegrityError
from statusbayes.models import SpamStatus
from django.contrib.contenttypes.models import ContentType


def make_msg(body, arg):
    """ Return a mesage from a model instance. """
    return build_msg(body, arg)

def do_filter(msg, instance):
    try:
        score = filter.score(msg)
    except:
        score = None
    try:
        status = SpamStatus(content_object=instance, score=score)
        status.save()
    except IntegrityError:
        pass

def filter_on_save(sender, instance, created, **kwargs):
    from djangobayes.filter import filter, build_msg
    msg = build_msg(instance.comment, {
        'from': instance.user_name,
    })
    if created:
        do_filter(msg, instance)
    else:
        ct = ContentType.objects.get(app_label="comments", model="comment")
        spamstatuses = SpamStatus.objects.filter(object_id=instance.pk, content_type__pk=ct.pk)
        if len(spamstatuses) == 0:
            do_filter(msg, instance)




